package com.example.petstore.controller;


import com.example.petstore.entity.LoginDTO;
import com.example.petstore.entity.UserLoginVO;
import com.example.petstore.service.IUserService;
import com.example.petstore.utils.JwtProperties;
import com.example.petstore.utils.JwtUtil;
import com.example.petstore.utils.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author DD
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO){
        UserLoginVO user1 = userService.login(loginDTO);
//         校验成功生成jwt
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user1.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user1.getId())
                .userName(user1.getUserName())
                .userAvatar(user1.getUserAvatar())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }
    @ApiOperation("注册接口")
    @PostMapping("register")
    public Result register( @RequestBody LoginDTO loginDTO){
        userService.register(loginDTO);
        return  Result.success();
    }
}
